#!/usr/bin/python -S
"""
child_process_test.py: Tests for child_process.py
"""

__author__ = 'Andy Chu'


import errno
import os
import signal
import sys
import time
import unittest

import child_process  # module under test
import ioloop
import timer
import log


def echo(chunk):
  print '>>>', repr(chunk)
  print '###', len(chunk)


class ChildProcessTest(unittest.TestCase):
  def setUp(self):
    pass

  def tearDown(self):
    pass

  def testExit(self):
    child_process.RegisterSignalHandlers()
    io_loop = ioloop.instance()
    p = child_process.ChildProcess(['find', '..'])
    def f(code, signum):
      print '@@@@@@@@@@@ exited with', code, signal
      # exited normally with code 0
      self.assertEqual(0, code)
      self.assertEqual(None, signum)

    p.On('exit', f)

    p.stdout.On('data', echo)

    io_loop.start()

  def testExitError(self):
    child_process.RegisterSignalHandlers()
    io_loop = ioloop.instance()
    p = child_process.ChildProcess(['false'])
    def f(code, signal):
      print '@@@@@@@@@@@ exited with', code, signal

    p.On('exit', f)

    p.stdout.On('data', echo)

    io_loop.start()

  def testExitSigKill(self):
    """Start up a sleep process, then kill it."""
    child_process.RegisterSignalHandlers()
    io_loop = ioloop.instance()

    p = child_process.ChildProcess(['sleep', '10'])

    def f(code, signum):
      print '@@@@@@@@@@@ exited with', code, signum
      self.assertEqual(None, code)
      self.assertEqual(signal.SIGINT, signum)

    p.On('exit', f)

    # Don't do anything with it -- TODO: ChildProcess needs to support opening
    # streams
    p.stdout.On('data', lambda x: None)

    # Kill it after one second
    def kill():
      print 'Killing', p.pid
      os.kill(p.pid, signal.SIGINT)
    timer.set_timeout(1, kill)

    io_loop.start()

  def testPipe(self):
    io_loop = ioloop.instance()
    p = child_process.ChildProcess(['cat'])
    # TODO: set timeout

    def AnotherWrite():
      print 'WRITING bar'
      p.stdin.write('bar')
    now = time.time()
    timer.set_timeout(2, AnotherWrite)

    print 'WRITING foo'
    p.stdin.write('foo')
    
    p.stdout.On('data', echo)
    io_loop.start()


if __name__ == '__main__':
  log.install_default_logger()
  unittest.main()
